﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Xml;
using System.Text.RegularExpressions;

namespace zazzle.net
{
    public partial class ZStore : System.Web.UI.UserControl
    {

        #region Control Parameters
        public string AssociateID {get; set;}
        public string ContributorHandle { get; set; }
        public int? ProductLineID{get;set;}
        // The numeric code for the Zazzle product line to display. If you want to show all products from a gallery, leave this blank.  
        // To get a product line number, click on a product line in a gallery.  In the URL you will see something like this:
        // http://www.zazzle.com/coatsofarms/products/cg-196595220567583981.  the number is the product line ID.
        // Leave this blank if you are pulling Zazzle Marketplace feeds.

        public bool? UseStylesheet { get; set; }
        public bool? UseImageCaching { get; set;}
        public bool? UseFeedCaching{get;set;}
        public bool? UseAnalytics { get; set; }
        public int? ImageCacheSeconds{get;set;}
        public int? FeedCacheSeconds{get;set;}

        public string Keywords{get;set;}

        public bool? ShowPagination{get;set;}
        public bool? ShowSorting{get;set;}

        public int? GridWidth; 

        private int? GridCellSizeInt;// = 152; //default
        public string GridCellSize
        {
            set
            {
                string val = value.ToLower(); 
                switch (val)
                {
                    case "tiny": GridCellSizeInt = 50; break;
                    case "small": GridCellSizeInt = 92; break;
                    case "medium": GridCellSizeInt = 152; break;
                    case "large": GridCellSizeInt = 210; break;
                    case "huge": GridCellSizeInt = 328; break;
                    default:
                        int ival = 0;
                        if (Int32.TryParse(val, out ival))
                            GridCellSizeInt = ival; 
                        break; 
                }
            }
            get { return GridCellSizeInt.HasValue? GridCellSizeInt.Value.ToString():""; }
        }
        public int? ShowHowMany {get;set;}
        public int? StartPage{get;set;}
        public string DefaultSort {get;set;}
        public string CurrentSort { get; set; }
        public bool? ShowProductDescription {get;set;}
        public bool? ShowByLine {get;set;}
        public bool? ShowProductTitle {get;set;}
        public bool? ShowProductPrice {get;set;}

        public int? ProductType { get; set; }
        // 128 Bumper Sticker
        // 137 Card
        // 144 Mouse pad
        // 145 Button 
        // 146 Keychain
        // 147 Magnet 
        // 148 Hat
        // 149 Bag 
        // 151 Tie
        // 153 Photo Sculpture 
        // 154 Apron
        // 156 Photo Print 
        // 158 Calendar
        // 167 Keds Shoes
        // 168 Mug 
        // 172 Postage Stamps
        // 186 Skateboards
        // 217 Sticker 
        // 228 Print (posters)
        // 231 Embroidered shirts
        // 232 Embroidered bags
        // 233 Embroidered hats
        // 235 T-Shirt 
        // 239 Postcards
        // 240 Profile Card

        #endregion
        #region local vars

        public int GridCellWidth;
        public int GridCellHeight;
        public string AssociateIDParam;
        public string KeywordsParam;
        public string AnalyticsLink; 

        public string CellBGColor;
        public int CellSpacing;

        string StyleSheetPath;

        bool CleanCache = false;

        string SortMethod, SortMode;

        // URLS used by the Zazzle Store Builder
        public string PoweredByZazzleButton = "http://www.zazzle.com/assets/graphics/logos/poweredByZazzle_v2.png";  
        public string ZazzleURLBase = "http://www.zazzle.com";

        #endregion

        protected void LoadParams()
        {
            //order of precedence: 
            //- control params
            //-querystring
            //-config file

            var s = ZStoreConfig.GetZStoreConfig();

            AssociateID = WebUtils.CoalParms(AssociateID, "associateId", s.AssociateID);
            ContributorHandle = WebUtils.CoalParms(ContributorHandle, "contributorHandle", s.ContributorHandle); 
            
            UseStylesheet=WebUtils.CoalParms(UseStylesheet, null, s.UseStylesheet);
            StyleSheetPath = s.StylesheetPath; 
            UseImageCaching = WebUtils.CoalParms(UseImageCaching, "useImageCaching", s.UseImageCache); 
            UseFeedCaching = WebUtils.CoalParms(UseFeedCaching, "useFeedCaching", s.UseFeedCache);

            ImageCacheSeconds = WebUtils.CoalParms(ImageCacheSeconds, "ImageCacheLifetime", s.ImageCacheSeconds);
            FeedCacheSeconds = WebUtils.CoalParms(FeedCacheSeconds, "FeedCacheLifetime", s.FeedCacheSeconds);

            CurrentSort=WebUtils.CoalParms(CurrentSort, "currentsort", null); 
            Keywords = WebUtils.CoalParms(Keywords, "keywords", s.Keywords);
            ShowPagination = WebUtils.CoalParms(ShowPagination, "showPagination", s.Paginate);

            ShowSorting = WebUtils.CoalParms(ShowSorting, "showSorting", s.Sorting);

            GridWidth = WebUtils.CoalParms(GridWidth, "gridWidth", s.GridWidth);
            GridCellSize = WebUtils.CoalParms(GridCellSize, "gridCellSize", s.CellSize);
            
            CellBGColor = s.CellBGColor;
            CellSpacing = s.CellSpacing;
            
            ShowHowMany = WebUtils.CoalParms(ShowHowMany, "", s.PageHowMany);
            StartPage = WebUtils.CoalParms(StartPage, "startPage", s.PageStart);

            DefaultSort = WebUtils.CoalParms(DefaultSort, "defaultSort", s.DefaultSort);

            ShowProductDescription = WebUtils.CoalParms(ShowProductDescription, "showProductDescription", s.ShowDescription);

            ShowByLine = WebUtils.CoalParms(ShowByLine, "showByLine", s.ShowByLine);

            ShowProductTitle = WebUtils.CoalParms(ShowProductTitle, "showProductTitle", s.ShowProductTitle);

            ShowProductPrice = WebUtils.CoalParms(ShowProductPrice, "showProductPrice", s.ShowProductPrice);

            ProductType = WebUtils.CoalParms(ProductType, "productType", s.ProductTypeID);
            ProductLineID = WebUtils.CoalParms(ProductLineID, "productLineId", s.ProductLineID); 
            //defaults if blank
            if(!GridWidth.HasValue || GridWidth.Value ==0)GridWidth = 900;
            if(!GridCellSizeInt.HasValue || GridCellSizeInt.Value ==0) GridCellSizeInt = 152;
            if (CellBGColor == null || CellBGColor.Length == 0) CellBGColor = "FFFFFF";
            if (CellSpacing == 0)CellSpacing = 9;
            if (!ShowHowMany.HasValue || ShowHowMany.Value == 0) ShowHowMany = 20;
            if (GridCellSize == null || GridCellSize.Length == 0) GridCellSize = "large";
            if (DefaultSort == null || DefaultSort.Length == 0) DefaultSort = "date_created";
            if (CurrentSort == null) CurrentSort = DefaultSort;
            if (!ShowProductDescription.HasValue) ShowProductDescription = true;
            if (!ShowByLine.HasValue) ShowByLine = true;
            if (!ShowProductTitle.HasValue) ShowProductTitle = true;
            if (!ShowProductPrice.HasValue) ShowProductPrice = true;
            if (!UseFeedCaching.HasValue) UseFeedCaching = false;
            if (!UseImageCaching.HasValue) UseImageCaching = false;
            if (!FeedCacheSeconds.HasValue) FeedCacheSeconds = 1800;
            if (!ImageCacheSeconds.HasValue) ImageCacheSeconds = 7200; 
            if(!StartPage.HasValue) StartPage = 1; 

            if(UseAnalytics.GetValueOrDefault(false)) 
                AnalyticsLink="onclick=\"pageTracker._link(this.href); return false;\"";
            else AnalyticsLink="";

            //calced fields
            GridCellWidth = GridCellSizeInt.Value + 6;
            GridCellHeight = GridCellSizeInt.Value + 4;
            
            AssociateIDParam = 
                (s.AssociateID != null 
                && s.AssociateID.Length >0 
                && !s.AssociateID.Equals("YOURASSOCIATEIDHERE"))?
                "?rf=" + s.AssociateID : "";

            if(DefaultSort.Equals("popularity"))
            {
                SortMethod="st=popularity";
                SortMode = "popularity";
            }
            if (DefaultSort.Equals("date_created"))
            {
                SortMethod = "st=date_created";
                SortMode = "date_created"; 
            }
            if (CurrentSort.Equals("popularity"))
            {
                SortMethod = "st=popularity";
                SortMode = "popularity"; 
            }
            if (CurrentSort.Equals("date_created"))
            {
                SortMethod = "st=date_created";
                SortMode = "date_created"; 
            }

            KeywordsParam = Server.UrlEncode("&keywords=" + Keywords);  //"&amp;keywords=".urlencode($_GET['keywords'])

            CleanCache = WebUtils.CoalParms((bool?)null, "clean_cache", false); 

        }


        protected void Page_Load(object sender, EventArgs e)
        {

            LoadParams();

            //TODO - handle caching here

            //TODO - handle request param paging with multiple grids on page
            // use multiple vars, or parse the array

            string DataURLBase = (ContributorHandle != null && ContributorHandle.Length > 0) ?
                    "http://feed.zazzle.com/" + ContributorHandle + "/feed"
                    : "http://feed.zazzle.com/feed";

            string cg= (ProductLineID.HasValue && ProductLineID.Value >0)?
                "&cg="+ProductLineID.ToString():"";

            string at = (AssociateID != null && AssociateID.Length > 0 && !AssociateID.Equals("YOURASSOCIATEIDHERE")) ?
                "&at=" + AssociateID : ""; 

            string URL = DataURLBase + "?"
                + SortMethod // + "&at=" + AssociateID
                + at
                + "&isz=" + GridCellSize
                + "&bg=" + CellBGColor
                + "&src=zeestore&pg=" + StartPage
                + cg + "&ps=" + ShowHowMany
                + "&ft=gb&opensearch=true&qs=" + Keywords
                + "&pt=" + ProductType;
		
            //process every call? or cache in postback? 
            //doing every time for now. 

            //RssToolkit.Rss.RssDocument zrss = RssToolkit.Rss.RssDocument.Load(new Uri(URL)); 
                //new System.Uri("http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml"));
            
            //check the cache here first.. 
   
            ////////////////////////////////

            //THIS IS A SIMPLER xml reader... move to this. 

            //XDocument feedXML =
            //XDocument.Load("http://feeds.encosia.com/Encosia");

            //var feeds = from feed in feedXML.Descendants("item")
            //            select new
            //            {
            //                Title = feed.Element("title").Value,
            //                Link = feed.Element("link").Value,
            //                Description = feed.Element("description").Value
            //            };

            ////////////////////////////////




            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(URL);
            ZItemList zil = new ZItemList(xDoc); 
             
            r.DataSource = zil; 
            r.DataBind(); 
         
         //   var zrss = zazzlerssRss.Load(new Uri(URL));

    //        int Showing = ((ShowHowMany.Value * StartPage.Value )-ShowHowMany.Value )+1;
    //        int ShowingEnd=ShowHowMany.Value  * StartPage.Value ; 

    //        // Get the total number of results from the opensearch: namespace in RSS
    //        int TotalNum = 0; 
    //        Int32.TryParse(zrss.Channel.TotalResults, out TotalNum);
    //        if ( ShowingEnd > TotalNum ) ShowingEnd = TotalNum; 
	
    //    $pagination = '';
    //    $paginationText = '';
    //    $paginationText2 = '';
  
    //// Figure out how many pages we have for pagination, use this to generate pagination control html
    //if ( $rs['items_count'] > 0 ) {
	
    //    $totalPages = ceil( $totalNum/$showHowMany );
    //    if($totalPages > 1 ) {
    //        $pagination = $paginationText;
		
    //    }
        
    //    // Figure out where to start and stop the pagination page listing	
    //    $paginationStart = $startPage - 5;
    //    $paginationEnd = $startPage + 5;
		
    //    $paginationBack = $startPage - 1;
    //    $paginationFwd = $startPage + 1;
		
    //    if( $paginationStart < 1 ) $paginationStart = 1;
    //    if( $paginationBack < 1 ) $paginationBack = 1;
		
    //    if( $paginationEnd > $totalPages ) $paginationEnd = $totalPages;
    //    if( $paginationFwd > $totalPages ) $paginationFwd = $totalPages;

         
        }

        public class ZItem{
            public string ImageSrc{set;get;}
            public string Title{set;get;}
            public string Link{set;get;}
            //public string DisplayTitle{set;get;} 
            public string Description{set;get;}
            //public string Byline{set;get;}
            public string DisplayPrice { set; get; }
            public string Artist{set;get;}

        }
        public class ZItemList : IEnumerable<ZItem>
        {
            List<ZItem> list; 
            
            public ZItemList(XmlDocument xd)//RssToolkit.Rss.RssChannel channel)//zazzlerssChannel channel)
            {
                //this is hacked from a doc reader, because couldnt figure out how to get custom properties using the 
                //rss toolkit. 
                list = new List<ZItem>(); 
                foreach (XmlElement el in xd.GetElementsByTagName("item"))
                {
                    var zi = new ZItem();
                    zi.Artist = el["artist"].InnerText; 
                    zi.Title = HttpUtility.UrlDecode(el["title"].InnerText);
                    zi.Description = HttpUtility.UrlDecode(el["description"].InnerText);
                    zi.ImageSrc = el["g:image_link"].InnerText;
                    zi.DisplayPrice = el["g:price"].InnerText;
                    zi.Link = el["link"].InnerText.Replace("&amp;ZCMP=gbase","") ; 
                    zi.Description = el["description"].InnerText; // Regex.Replace(el[""].InnerText,
                    //show first 10 words only
                    var desclist = zi.Description.Split(' '); 
                    if(desclist.Length >10){
                        zi.Description = ""; 
                        for(int i = 0; i < 10; i++)
                            zi.Description += desclist[i] + " "; 
                        zi.Description += "... ";
                    }
                    
                        //$productId = $value['g:id'];
                    //$pubDate = $value['pubDate'];
                    //$artist = $value['artist'];
                    //$shortdescription = '';
                    //// strip any html from the description
                    //$description = preg_replace( "/<[^>]+>/", '', $description );
                    //$title = preg_replace( "/<[^>]+>/", '', $title );
                    //$shortdescription = preg_replace( "/<[^>]+>/", '', $shortdescription );
                    //if( $showProductDescription == true ) {
                    //    $description = preg_replace( "/\.\.\./", '... ', $description );
                    //    $description = preg_replace( "/\,/", ', ', $description );
                    //    $descriptionWords = preg_split("/[\s]+/", $description );

                    //    for( $i = 0; $i <= 10; ++$i ) {
                    //            $shortdescription .= $descriptionWords[$i] . ' ';
                    //    }

                    //    if( sizeof( $descriptionWords ) > 10 ) $shortdescription .= '...';
                    //}

                    list.Add(zi); 
                    
                }

            }
            IEnumerator<ZItem> IEnumerable<ZItem>.GetEnumerator()
            {

                foreach (var itm in list)
                {
                    yield return itm; 
                }


                //    yield return new ZItem() { 
                //        Title = "test", Byline = "x", Description = "gg", DisplayPrice = "12.22", DisplayTitle = "dt", ImageSrc = "xxx", Link = "xxxxx" };
                //}
            }
            IEnumerator IEnumerable.GetEnumerator()
            {
                return  ((IEnumerable<ZItem>)this).GetEnumerator();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {

            //NOTE- the "UseStylesheet" will not be assigned yet from the
            //config file or qs. this will only get parameters...
            //(assuming this fires before pageload)

            //if adding css link... 
            if(Page.Header.FindControl("zs_css")==null && UseStylesheet.GetValueOrDefault())
            {
                var style = new System.Web.UI.HtmlControls.HtmlLink(); 
                style.Attributes.Add("href", ResolveUrl("~/css/zstore.css")); 
                style.Attributes.Add("type", "text/css"); 
                style.Attributes.Add("rel", "stylesheet"); 

                Page.Header.Controls.Add(style); 
            }
        }
        
    }
}